<template>
    <div>
        <div>
            <el-form :model="formParam" label-width="90px" :inline="true">
                <el-form-item label="仓库：">
                    <el-select v-model="formParam.depotId" placeholder="选择仓库" clearable filterable multiple
                        collapse-tags>
                        <el-option v-for="item in depot" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="月份：">
                    <el-date-picker v-model="formParam.date" type="month" placeholder="请选择月份" format="YYYY-MM"
                        date-format="YYYY/MM" value-format="YYYY-MM" />
                </el-form-item>
                <el-form-item label="商品信息：">
                    <el-input v-model="formParam.name" placeholder="条码/名称/规格/型号" clearable></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="findPage">查询</el-button>
                    <el-button @click="exportBtn">
                        <el-icon class="el-icon--left">
                            <Download />
                        </el-icon>
                        导出
                    </el-button>
                    <el-button type="primary" size="default" link @click="visible = !visible">
                        {{ visible ? '收起' : '展开' }}
                        <el-icon :style="{ transform: visible ? 'rotate(180deg)' : 'rotate(0deg)' }">
                            <ArrowUp />
                        </el-icon>
                    </el-button>
                </el-form-item>
                <div>
                    <div v-if="visible">
                        <el-form-item label="类别：">
                            <el-tree-select v-model="formParam.categoryId" :data="category" check-strictly
                                :props="{ children: 'children', label: 'name', value: 'id' }" :default-expand-all="true"
                                :render-after-expand="false" placeholder="请选择商品类别" clearable>
                            </el-tree-select>
                        </el-form-item>
                    </div>
                </div>
            </el-form>

        </div>
        <div>
            <el-table :data="page.records" ref="tableRef" border show-summary :summary-method="getSummaries" stripe
                max-height="489px" v-loading="loading">
                <el-table-column type="index" label="#" align="center" width="60" />
                <el-table-column v-for="col in tableHeader" :prop="col.prop" :key="col.id" :label="col.label"
                    :width="col.width" :sortable="col.sortable">
                </el-table-column>
            </el-table>
        </div>

        <div>
            <Pagination :current="page.current" :page-size="page.size" :total="page.total" @change=""
                @update:pageSize="sizeChange" @update:current="currentChange" />
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { exportTable } from '@/utils/xlsx';
import { getInOutStockReportTableHead } from '@/components/material_bill_detail/js/getTableHead'
import request from '@/api/request';

import Pagination from '@/components/pagination/Index.vue'

const tableRef = ref(null)

const loading = ref(false)

let formParam = ref({})
let depot = ref([])
let category = ref([])
let visible = ref(false)
let tableHeader = ref([])

const page = ref({
    current: 1,
    size: 5,
    pages: 1,
    total: 1,
    records: null
});


const findPage = async () => {
    loading.value = true
    getDate()

    let depotId = []
    if (formParam.value.depotId) {
        depotId = formParam.value.depotId.join(',')
    }

    request.get('report/findInOutStockReportPage', {
        params: {
            depotId,
            createTime: formParam.value.createTime,
            endTime: formParam.value.endTime,
            name: formParam.value.name,
            categoryId: formParam.value.categoryId,
            current: page.value.current, size: page.value.size
        }
    }).then(resp => {
        page.value = resp.data

    })
    setInterval(loading.value = false, 20000);
}

const findDepotByTenantId = async () => {
    await request.get("depot/findDepotByTenantId")
        .then(resp => {
            depot.value = resp.data
        })
}


const findCategoryByTenantId = async () => {
    await request.get("cam/findCategoryByTenantId")
        .then(resp => {
            category.value = resp.data
        })
}


onMounted(() => {
    findDepotByTenantId()
    findCategoryByTenantId()
    getTableHead()

    findPage()
})

const getDate = () => {
    let date = new Date();
    if (formParam.value.date) {
        const [year, month] = formParam.value.date.split('-');
        date = new Date(year, month - 1, 1)
    }
    const year = date.getFullYear();
    const month = date.getMonth(); // 注意：getMonth() 返回的月份是从0开始的（0代表1月，11代表12月）  

    // 获取当前月份的第一天  
    const firstDay = new Date(year, month, 1);
    const firstDayFormatted = formatDate(firstDay);

    // 获取当前月份的最后一天  
    const lastDay = new Date(year, month + 1, 0); // month + 1 的0号表示上一个月的最后一天  
    // 设置最后一天的时间为 23:59:59  
    lastDay.setHours(23, 59, 59);
    const lastDayFormatted = formatDate(lastDay);

    formParam.value.createTime = firstDayFormatted;
    formParam.value.endTime = lastDayFormatted;

    // console.log('当前月份的第一天:', firstDayFormatted); // 输出格式为 YYYY-MM-DD HH:mm:ss  
    // console.log('当前月份的最后一天:', lastDayFormatted); // 输出格式为 YYYY-MM-DD HH:mm:ss  
}

// 格式化日期为 YYYY-MM-DD HH:mm:ss  
function formatDate(date) {
    const padZero = (num) => (num < 10 ? '0' + num : num);
    const year = date.getFullYear();
    const month = padZero(date.getMonth() + 1); // 月份从0开始，所以加1  
    const day = padZero(date.getDate());
    const hours = padZero(date.getHours());
    const minutes = padZero(date.getMinutes());
    const seconds = padZero(date.getSeconds());

    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

/**
 * 设置表尾合计
 * @param param 表格数据
 */

const getSummaries = (param) => {
    const { columns, data } = param;
    const sums = [];

    columns.forEach((column, index) => {
        if (index === 0) {
            sums[index] = "合计";
            return;
        }
        if (Array.isArray(data)) {
            const values = data.map((item) => Number(item[column.property]));
            // 想合并哪些列就在这里指定
            if (column.property === "lastMonthNumber" || column.property === "storageNumber" ||
                column.property === "backNumber" || column.property === "monthNumber" || column.property === "money"
            ) {
                sums[index] = values.reduce((prev, curr) => {
                    const value = Number(curr);
                    if (!isNaN(value)) {
                        return prev + curr;
                    } else {
                        return prev;
                    }
                }, 0);
            }
        }
    });
    return sums;
}

const exportBtn = () => {
    exportTable(tableRef, '进销存统计报表')
}

const getTableHead = () => {
    tableHeader.value = getInOutStockReportTableHead()
}

const sizeChange = (pageSize) => {
    page.value.size = pageSize;
    findPage()
}

const currentChange = (pageCurrent) => {
    page.value.current = pageCurrent;
    findPage()
}

</script>

<style scoped>
.el-select {
    width: 250px;
}

.el-input {
    width: 250px;
}
</style>
